import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'
import { getUserToken } from '@/utils/userAuth'

// 布局组件
import MainLayout from '@/layouts/MainLayout.vue'

// 页面组件
const DiscoverView = () => import('@/views/home/DiscoverView.vue')
const NotificationView = () => import('@/views/home/NotificationView.vue')
const UserProfileView = () => import('@/views/user/UserProfile.vue')
const PublishView = () => import('@/views/home/PublishView.vue')
const LoginView = () => import('@/views/user/Login.vue')
const RegisterView = () => import('@/views/user/Register.vue')

const routes = [
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Home',
        component: DiscoverView
      },
      {
        path: 'notification',
        name: 'Notification',
        component: NotificationView
      },
      {
        path: 'profile',
        name: 'Profile',
        component: UserProfileView,
        meta: { requiresAuth: true }
      },
      {
        path: 'publish',
        name: 'Publish',
        component: PublishView
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginView,
    meta: { requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: RegisterView,
    meta: { requiresGuest: true }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = getUserToken()
  
  // 如果路由需要认证且没有token，跳转到登录页
  if (to.meta.requiresAuth && !token) {
    next({ name: 'Login' })
    return
  }
  
  // 如果路由需要访客模式且已登录，跳转到首页
  if (to.meta.requiresGuest && token) {
    next({ name: 'Home' })
    return
  }
  
  // 如果已登录但用户信息未加载，加载用户信息
  if (token && !userStore.userInfo) {
    console.log('正在加载用户信息...')
    userStore.fetchCurrentUserInfo().then(() => {
      next()
    }).catch((error) => {
      console.error('获取用户信息失败，使用默认数据', error)
      // 即使获取用户信息失败，也继续导航，因为我们有默认数据
      next()
    })
    return
  }
  
  next()
})

export default router